/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p/>
 * Compile: JDK 1.6+
 * <p/>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p/>
 * 公司名称：江苏欧索软件有限公司
 * <p/>
 * 公司地址：中国苏州科技城青山路1号
 * <p/>
 * 网址: http://www.oceansoft.com.cn
 * <p/>
 * 版本: 苏州公安统一用户管理平台1.0
 * <p/>
 * 作者: 090922(陈伟)
 * <p/>
 * 文件名:DeptManagerController.java
 * <p/>
 * 类产生时间: 2012-5-29 上午12:53:18
 * <p/>
 * 负责人: 090922(陈伟)
 * <p/>
 * Email:javacspring@gmail.com
 * <p/>
 * 所在组 : 苏州公安统一用户管理平台
 * <p/>
 * 所在部门: 电信/国土——技术二部
 * <p/>
 * <p/>
 */
package com.oceansoft.core.jxkh.controller;

import com.hui.platform.system.exception.HuiException;
import com.hui.platform.system.utility.StringUtil;
import com.oceansoft.core.common.constant.Constant;
import com.oceansoft.core.common.util.DatetimeUtil;
import com.oceansoft.core.common.util.Pagination;
import com.oceansoft.core.controller.util.ApiResult;
import com.oceansoft.core.domain.Message;
import com.oceansoft.core.domain.SysUser;
import com.oceansoft.core.jxkh.domain.*;
import com.oceansoft.core.jxkh.service.IWorkLogService;
import com.oceansoft.core.rcgz.service.IRcgzService;
import com.oceansoft.core.service.ISysUserService;
import com.oceansoft.core.service.IUUMSRoleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 周纪实，月纪实controller
 *
 * @author acer
 */
@Controller
@RequestMapping("/worklog")
public class WorkLogController {

    @Resource
    private IUUMSRoleService roleService;
    @Resource
    private ISysUserService userService;
    @Resource
    private IWorkLogService workLogService;
    @Resource
    private IRcgzService rcgzService;

    @RequestMapping(value = "list/{pageIndex}/{policeNum}")
    public ApiResult querybycondition(HttpServletRequest request, @PathVariable("pageIndex") String pageIndex, @PathVariable("policeNum") String policeNum) {
        if (StringUtil.isNull(pageIndex)) {
            pageIndex = "1";
        }
        ApiResult apiResult = new ApiResult();
        HashMap<String, String> map = new HashMap<>();
        map.put("policeNum", policeNum);
        map.put("pageIndex", pageIndex);
        // 读取角色
        Map<String, Object> roles = roleService.findRoleByUser(policeNum);
        SysUser user = userService.findUserByPoliceNum(policeNum);
        Pagination<WorkLog> list = null;
        try {
            list = workLogService.querybycondition(map, user);
        } catch (HuiException e) {
            e.printStackTrace();
        }
        apiResult.success(list);
        return apiResult;
    }


    //日报填写

    /**
     * 个人日报新增
     */
    @RequestMapping(value = "saveDaliywork", method = POST)
    public void savework(HttpServletRequest request, Daliywork daliywork, ModelMap modelMap) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        Message message = new Message("操作成功");
        message.setStatus(Constant.RESULT_SUCC);
        daliywork.setPoliceNum(user.getPoliceNum());
        String index1 = request.getParameter("index1");
        String index2 = request.getParameter("index2");
        String index3 = request.getParameter("index3");
        try {

            Integer dbid = daliywork.getDbid();
            if (dbid == null || dbid == Integer.MIN_VALUE) {
                dbid = workLogService.saveDailywork(daliywork);
            } else {//清空之前保存的数据
                workLogService.deleteDailyWorkContent(dbid);
            }
            //保存type1的数据
            for (int i = 1; i <= Integer.parseInt(index1); i++) {
                if (com.oceansoft.core.common.util.StringUtil.isNotNullAndBlank(request.getParameter("content1" + i))) {
                    Daliyworkcontent content = new Daliyworkcontent();
                    content.setType("1");
                    content.setContent(request.getParameter("content1" + i));
                    content.setDailyid(dbid);
                    workLogService.saveDailyworkcontent(content);
                }
            }
            //保存type2的数据
            for (int i = 1; i <= Integer.parseInt(index2); i++) {
                if (com.oceansoft.core.common.util.StringUtil.isNotNullAndBlank(request.getParameter("content2" + i))) {
                    Daliyworkcontent content = new Daliyworkcontent();
                    content.setType("2");
                    content.setContent(request.getParameter("content2" + i));
                    content.setDailyid(dbid);
                    workLogService.saveDailyworkcontent(content);
                }
            }
            //保存type3的数据
            for (int i = 1; i <= Integer.parseInt(index3); i++) {
                if (com.oceansoft.core.common.util.StringUtil.isNotNullAndBlank(request.getParameter("content3" + i))) {
                    Daliyworkcontent content = new Daliyworkcontent();
                    content.setType("3");
                    content.setContent(request.getParameter("content3" + i));
                    content.setDailyid(dbid);
                    workLogService.saveDailyworkcontent(content);
                }
            }
        } catch (HuiException e) {
            e.printStackTrace();
            message.setStatus(Constant.RESULT_FAILD);
            message.setBody(e.getMessage());
        }
        modelMap.addAttribute("data", message);
    }

    /**
     * 本周个人日报列表
     */
    @RequestMapping(value = "weekDaliywork/{policeNum}/{startDate}/{endDate}")
    public ApiResult weekDaliywork(HttpServletRequest request, @PathVariable("policeNum") String policeNum, @PathVariable("startDate") String startDate, @PathVariable("endDate") String endDate) {
        ApiResult apiResult = new ApiResult();
        HashMap<String, String> map = new HashMap<>();
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("policeNum", policeNum);
        List<Daliywork> list = new ArrayList<Daliywork>();
        try {
            list = workLogService.weekDaliywork(map);
        } catch (HuiException e) {
            e.printStackTrace();
        }
        return apiResult.success(list);
    }

    //	//周报填写
//	/**
//	 * 个人周报新增&月报
//	 */
    @RequestMapping(value = "saveWorkLog", method = POST)
    public ApiResult saveWorkLog(HttpServletRequest request, WorkLog workLog) {
        try {
            workLogService.saveWeekwork(workLog);
        } catch (HuiException e) {
            e.printStackTrace();
        }
        return new ApiResult();
    }

    /**
     * 获取当日工作内容和签到信息
     */
    @RequestMapping(value = "dailyWorkedit.html")
    public String monthsWeekwork(HttpServletRequest request, ModelMap modelMap) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        String workdate = request.getParameter("workdate");
        String type = request.getParameter("type");
        Daliywork dailywork = workLogService.findDaliyworkByDate(user.getPoliceNum(), workdate);
        modelMap.addAttribute("data", dailywork);
        modelMap.addAttribute("workdate", workdate);
        modelMap.addAttribute("type", type);
        return "dailyWork/edit";
    }


    /**
     * 获取当日工作内容和签到信息
     */
    @RequestMapping(value = "dailyWorkInfo.json")
    public void dailyWorkInfo(HttpServletRequest request, ModelMap modelMap) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        String workdate = request.getParameter("workdate");
        List<Daliyworkcontent> list1 = new ArrayList<Daliyworkcontent>();
        try {
            //根据workdate获取当日的签到信息
            list1 = workLogService.dailyWorkContent(user.getPoliceNum(), workdate, "");
        } catch (HuiException e) {
            e.printStackTrace();
        }
        if (list1.size() > 0) {
            modelMap.addAttribute("hasList", true);
            modelMap.addAttribute("list", list1);
        } else {
            modelMap.addAttribute("hasList", false);
        }
    }

    @RequestMapping(value = "wdzblist.json")
    public void wdzbList(HttpServletRequest request, ModelMap model) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        String order = request.getParameter("order");
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        String type = request.getParameter("type");
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        HashMap<String, String> paramap = new HashMap<String, String>();
        paramap.put("offset", offset);
        paramap.put("limit", limit);
        paramap.put("order", order);
        paramap.put("start", start);
        paramap.put("end", end);
        paramap.put("type", type);
        Pagination<WorkLog> page = workLogService.myWorkList(paramap, user);
        model.addAttribute("rows", page.getList());
        model.addAttribute("total", page.getTotalRows());
    }


    @RequestMapping(value = "wdzb.html")
    public String wdzb(HttpServletRequest request, ModelMap model) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        String type = request.getParameter("type");
        Map<String, String> map = getDateSection(type);
        boolean  result = workLogService.checkIsAdd(user, map);
        model.addAttribute("result", result);
        model.addAttribute("type", type);
        return "jump/wdzb";
    }


    @RequestMapping(value = "editWdzb/{dbid}.html")
    public String editWdzb(@PathVariable("dbid") int dbid, HttpServletRequest request, ModelMap model) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        WorkLog workLog = new WorkLog();
        String content1 = "";
        String content2 = "";
        String content3 = "";
        String type = request.getParameter("type");
        if (dbid == -1) {//新增
            //根据type获取上周，上月，上季度工作情况
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            if ("1".equals(type)) {
                list = workLogService.findLastWeekWork(user.getPoliceNum(), "");
            } else  {
                list = workLogService.findLastMonthWork(user.getPoliceNum(), type);
            }
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).containsKey("WORKSTARTDATE")) {
                    list.get(i).put("WORKSTARTDATE", list.get(i).get("WORKSTARTDATE").toString().replace("00:00:00.0", ""));
                }
                if (list.get(i).containsKey("WORKENDDATE")) {
                    list.get(i).put("WORKENDDATE", list.get(i).get("WORKENDDATE").toString().replace("00:00:00.0", ""));
                }
                if (list.get(i).containsKey("WORKDATE")) {
                    list.get(i).put("WORKDATE", list.get(i).get("WORKDATE").toString().replace("00:00:00.0", ""));
                }
            }
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).containsKey("WORKSTARTDATE")) {
                    if(null!=list.get(i).get("CONTENT1")){
                        content1 += list.get(i).get("WORKSTARTDATE") + "至" + list.get(i).get("WORKENDDATE") + ":" + list.get(i).get("CONTENT1") + "####";
                    }
                    if(null!=list.get(i).get("CONTENT2")){
                        content2 += list.get(i).get("WORKSTARTDATE") + "至" + list.get(i).get("WORKENDDATE") + ":" + list.get(i).get("CONTENT2") + "####";
                    }
                    if(null!=list.get(i).get("CONTENT3")){
                        content3 += list.get(i).get("WORKSTARTDATE") + "至" + list.get(i).get("WORKENDDATE") + ":" + list.get(i).get("CONTENT3") + "####";
                    }
                } else {
                    if(null!=list.get(i).get("CONTENT1")){
                        content1 += list.get(i).get("WORKDATE") + ":" + list.get(i).get("CONTENT1") + "####";
                    }
                    if(null!=list.get(i).get("CONTENT2")){
                        content2 += list.get(i).get("WORKDATE") + ":" + list.get(i).get("CONTENT2") + "####";
                    }
                    if(null!=list.get(i).get("CONTENT3")){
                        content3 += list.get(i).get("WORKDATE") + ":" + list.get(i).get("CONTENT3") + "####";
                    }
                }
            }
            if(content1.length()>4){
                content1 = content1.substring(0, content1.length() - 4);
            }
            if(content2.length()>4){
                content2 = content2.substring(0, content2.length() - 4);
            }
            if(content3.length()>4){
                content3 = content3.substring(0, content3.length() - 4);
            }
        } else {
            workLog = workLogService.findWorkLog(dbid);
        }
        model.addAttribute("data", workLog);
        model.addAttribute("dbid", dbid);
        model.addAttribute("type", type);
        model.addAttribute("content1", content1);
        model.addAttribute("content2", content2);
        model.addAttribute("content3", content3);
        return "worklog/editWdzb";
    }

    /**
     * 获取当日工作内容和签到信息
     */
    @RequestMapping(value = "weekWorkInfo/{dbid}.json")
    public void dailyWorkInfo(@PathVariable("dbid") int dbid, HttpServletRequest request, ModelMap modelMap) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        List<WorkLogcontent> list1 = new ArrayList<WorkLogcontent>();
        //根据workdate获取当日的签到信息
        list1 = workLogService.weekWorkInfo(user.getPoliceNum(), dbid);
        if (list1.size() > 0) {
            modelMap.addAttribute("hasList", true);
            modelMap.addAttribute("list", list1);
        } else {
            modelMap.addAttribute("hasList", false);
        }
        //return "dailyWork/edit";
    }

//周报，月报，季度报

    /**
     * 个人周报
     */
    @RequestMapping(value = "saveWorklog", method = POST)
    public void saveWorklog(HttpServletRequest request, WorkLog workLog, ModelMap modelMap) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        Message message = new Message("操作成功");
        message.setStatus(Constant.RESULT_SUCC);
        workLog.setPoliceNum(user.getPoliceNum());
        workLog.setDeptid(user.getDeptId());
        workLog.setUsername(user.getName());
        String index1 = request.getParameter("index1");
        String index2 = request.getParameter("index2");
        String index3 = request.getParameter("index3");
        String type = request.getParameter("type");
        Map<String, String> map = getDateSection(type);
        workLog.setWorkstartdate(map.get("firstDay"));
        workLog.setWorkenddate(map.get("lastDay"));
        try {
            Integer dbid = workLog.getDbid();
            if (dbid == null || dbid == -1) {
                dbid = workLogService.saveWeekwork(workLog);
            } else {//清空之前保存的数据
                workLogService.deleteWeekworkContent(dbid);
            }
            //保存type1的数据
            for (int i = 1; i <= Integer.parseInt(index1); i++) {
                if (com.oceansoft.core.common.util.StringUtil.isNotNullAndBlank(request.getParameter("content1" + i))) {
                    WorkLogcontent content = new WorkLogcontent();
                    content.setType("1");
                    content.setWorkitem(request.getParameter("content1" + i));
                    content.setLogid(dbid);
                    workLogService.saveWorkLogContent(content);
                }
            }
            //保存type2的数据
            for (int i = 1; i <= Integer.parseInt(index2); i++) {
                if (com.oceansoft.core.common.util.StringUtil.isNotNullAndBlank(request.getParameter("content2" + i))) {
                    WorkLogcontent content = new WorkLogcontent();
                    content.setType("2");
                    content.setWorkitem(request.getParameter("content2" + i));
                    content.setLogid(dbid);
                    workLogService.saveWorkLogContent(content);
                }
            }
            //保存type3的数据
            for (int i = 1; i <= Integer.parseInt(index3); i++) {
                if (com.oceansoft.core.common.util.StringUtil.isNotNullAndBlank(request.getParameter("content3" + i))) {
                    WorkLogcontent content = new WorkLogcontent();
                    content.setType("3");
                    content.setWorkitem(request.getParameter("content3" + i));
                    content.setLogid(dbid);
                    workLogService.saveWorkLogContent(content);
                }
            }
        } catch (HuiException e) {
            e.printStackTrace();
            message.setStatus(Constant.RESULT_FAILD);
            message.setBody(e.getMessage());
        }
        modelMap.addAttribute("data", message);
    }

    /**
     * 获取当日工作内容和签到信息
     */
    @RequestMapping(value = "deleteData/{dbid}.json")
    public void deleteData(@PathVariable("dbid") int dbid, HttpServletRequest request, ModelMap modelMap) {
        workLogService.deleteData(dbid);
    }



    /**
     * 当前时间，当前格式的纪实是否已经填写
     */
    @RequestMapping(value = "checkIsAdd")
    public void checkIsAdd(HttpServletRequest request, ModelMap modelMap) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        String type = request.getParameter("type");
        boolean result = false;
        Map<String, String> map = getDateSection(type);
        result = workLogService.checkIsAdd(user, map);
        modelMap.addAttribute("result", result);
    }


    public Map<String, String> getDateSection(String type) {
        Map<String, String> map = new HashMap<String, String>();
        if ("1".equals(type)) {
            map = DatetimeUtil.getLastWeek();
        } else if ("2".equals(type)) {
            map = DatetimeUtil.getLastMonth();
        } else if ("3".equals(type)) {
            map = DatetimeUtil.getLastQuarter();
        }
        map.put("type", type);
        return map;
    }



    @RequestMapping(value = "wdyblist.json")
    public void wdybList(HttpServletRequest request, ModelMap model) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        String order = request.getParameter("order");
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        String type = request.getParameter("type");
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        HashMap<String, String> paramap = new HashMap<String, String>();
        paramap.put("offset", offset);
        paramap.put("limit", limit);
        paramap.put("order", order);
        paramap.put("start", start);
        paramap.put("end", end);
        paramap.put("type", type);
        Pagination<Ydxj> page = workLogService.wdybList(paramap, user);
        model.addAttribute("rows", page.getList());
        model.addAttribute("total", page.getTotalRows());
    }


    @RequestMapping(value = "wdyb.html")
    public String wdyb(HttpServletRequest request, ModelMap model) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        String type = request.getParameter("type");
        String dateSection = "2";
        if("1".equals(type)){
            dateSection="2";
        }
        if("2".equals(type)){
            dateSection="3";
        }
        Message message = new Message("操作成功");
        message.setStatus(Constant.RESULT_SUCC);
        Map<String, String> map = getDateSection(dateSection);
       boolean result = workLogService.checkIsAddyb(map,user);
        model.addAttribute("result", result);
        model.addAttribute("type", type);
        return "wdyb/wdyb";
    }


    @RequestMapping(value = "editWdyb/{dbid}.html")
    public String editWdyb(@PathVariable("dbid") int dbid, HttpServletRequest request, ModelMap model) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        Ydxj ydxj = new Ydxj();
        String content = "";
        String type = request.getParameter("type");
        if (dbid == -1) {//新增
            //根据type获取上周，上月，上季度工作情况
            List<Map<String, Object>> list = workLogService.findLastMonthWork(user.getPoliceNum(), String.valueOf(Integer.parseInt(type)+1));
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).containsKey("WORKSTARTDATE")) {
                    list.get(i).put("WORKSTARTDATE", list.get(i).get("WORKSTARTDATE").toString().replace("00:00:00.0", ""));
                }
                if (list.get(i).containsKey("WORKENDDATE")) {
                    list.get(i).put("WORKENDDATE", list.get(i).get("WORKENDDATE").toString().replace("00:00:00.0", ""));
                }
                if (list.get(i).containsKey("WORKDATE")) {
                    list.get(i).put("WORKDATE", list.get(i).get("WORKDATE").toString().replace("00:00:00.0", ""));
                }
            }
            for (int i = 0; i < list.size(); i++) {
                    if(null!=list.get(i).get("CONTENT1")){
                        content += list.get(i).get("WORKSTARTDATE") + "至" + list.get(i).get("WORKENDDATE") + "日常工作:" + list.get(i).get("CONTENT1") + "####";
                    }
                    if(null!=list.get(i).get("CONTENT2")){
                    content += list.get(i).get("WORKSTARTDATE") + "至" + list.get(i).get("WORKENDDATE") + "重点工作:" + list.get(i).get("CONTENT2") + "####";
                }
                if(null!=list.get(i).get("CONTENT3")){
                    content += list.get(i).get("WORKSTARTDATE") + "至" + list.get(i).get("WORKENDDATE") + "交办工作:" + list.get(i).get("CONTENT3") + "####";
                }
            }
            if(content.length()>4){
                content = content.substring(0, content.length() - 4);
            }
        } else {
            ydxj = workLogService.findYdxj(dbid);
        }
        model.addAttribute("data", ydxj);
        model.addAttribute("dbid", dbid);
        model.addAttribute("type", type);
        model.addAttribute("content", content);
        return "wdyb/editWdyb";
    }

    /**
     * 个人周报
     */
    @RequestMapping(value = "saveYdxj", method = POST)
    public void saveYdxj(HttpServletRequest request, Ydxj ydxj, ModelMap modelMap) {
        SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
        String type= request.getParameter("type");
        String dateSection = "2";
        if("1".equals(type)){
            dateSection="2";
        }
        if("2".equals(type)){
            dateSection="3";
        }
        Message message = new Message("操作成功");
        message.setStatus(Constant.RESULT_SUCC);
        ydxj.setPolicenum(user.getPoliceNum());
        Map<String, String> map = getDateSection(dateSection);
        ydxj.setWorkstartdate(map.get("firstDay"));
        ydxj.setWorkenddate(map.get("lastDay"));
        try {
            workLogService.saveYdxj(ydxj);
        } catch (HuiException e) {
            e.printStackTrace();
        }
        modelMap.addAttribute("data", message);
    }
    /**
     * 个人周报
     */
    @RequestMapping(value = "deleteYdxj/{dbid}")
    public void deleteYdxj(@PathVariable("dbid") int dbid,HttpServletRequest request, ModelMap modelMap) {
        workLogService.deleteYdxj(dbid);
    }


}
